package com.xhorse.lockplatform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.CCPRestSDK;
import com.xhorse.lockplatform.comm.constant.ConstantString;
import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.SmsBaseInfo;
import com.xhorse.lockplatform.comm.service.BaseService;
import com.xhorse.lockplatform.comm.util.*;
import com.xhorse.lockplatform.dao.mapper.XhSmsLogMapper;
import com.xhorse.lockplatform.model.XhSmsLog;
import com.xhorse.lockplatform.service.RegistrantService;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@Service
public class RegistrantServiceImpl extends BaseService<XhSmsLog> implements RegistrantService {

    @Autowired
    private XhSmsLogMapper xhSmsLogMapper;
    @Autowired
    private SmsBaseInfo smsBaseInfo;

    /**
     * 登陆模块
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public String checkLogin(String username, String password) {
        RequestBody fromBody = new FormBody.Builder()
                .add("username", username).add("password", password)
                .add("cmd", "14").build();
        // 服务器请求登录
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, fromBody, encryptToken(username));
        return result;
    }

    /**
     * 注册模块
     *
     * @param cellPhone
     * @param password
     * @param ip
     * @return
     */
    @Override
    public String Registration(String cellPhone, String password, String ip) {
        XhSmsLog xhSmsLog = xhSmsLogMapper.selectByUserName(cellPhone);
        String result = null;
        if (xhSmsLog != null && xhSmsLog.getFlag() == 1) {
            RequestBody requestBody = new FormBody.Builder()
                    .add("username", cellPhone).add("password", password)
                    .add("ip", ip).add("cmd", "16").build();
            // 服务器请求注册
            result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, encryptToken(ConstantString.USERNAME));
            xhSmsLog.setFlag(0);
            xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
        }
        return result;
    }

    // 短信发送模块
    @Override
    public boolean sendSMS(String cellPhone) {
        CCPRestSDK restAPI = new CCPRestSDK();
        // 初始化服务器地址和端口，服务器地址不需要写https：//
        restAPI.init(smsBaseInfo.getIp(), smsBaseInfo.getPort());
        // 初始化应用ID
        restAPI.setAccount(smsBaseInfo.getAccount(),
                smsBaseInfo.getToken());
        restAPI.setAppId(smsBaseInfo.getAppId());
        // 生成验证码
        int SMScode = (int) ((Math.random() * 9 + 1) * 100000);
        // 手机号和验证码存放于数据库，用于后续验证
        XhSmsLog xhSmsLog = new XhSmsLog();
        xhSmsLog.setUserName(cellPhone);
        xhSmsLog.setSms(SMScode + "");
        xhSmsLog.setFlag(0);
        xhSmsLog.setTime(new Date());
        HashMap<String, Object> result = restAPI.sendTemplateSMS(cellPhone,
                smsBaseInfo.getTemplateId(), new String[]{SMScode + "", DateUtils.nowDateString(DateUtils.CN_DATE_PATTERN), "手机短信验证"});
        if ("000000".equals(result.get("statusCode"))) { // 若发送成功，则入库验证码信息
            XhSmsLog temp = xhSmsLogMapper.selectByUserName(cellPhone);
            if (temp == null) {
                xhSmsLogMapper.insertSelective(xhSmsLog);
            } else {
                xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
            }
            return true;
        } else {
            // 异常返回输出错误码和错误信息
            return false;
        }
    }

    /**
     * 发送邮箱验证码
     */
    @Override
    public boolean sendEMS(String username) {
        RequestBody requestBody = new FormBody.Builder().add("username",
                username).build();
        String result = sendMsg(ConstantString.PHP_URL_GETEMAIL, requestBody, encryptToken(username));
        JSONObject object = JSONObject.parseObject(result);
        if (ResultEnum.SUCCESS.getCode().equals(object.getString("status"))) {
            XhSmsLog xhSmsLog = new XhSmsLog();
            xhSmsLog.setUserName(username);
            xhSmsLog.setFlag(0);
            xhSmsLog.setTime(new Date());
            XhSmsLog temp = xhSmsLogMapper.selectByUserName(username);
            if (temp == null) {
                xhSmsLogMapper.insertSelective(xhSmsLog);
            } else {
                xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
            }
            return true;
        }
        return false;
    }

    // 验证码校验模块
    @Override
    public boolean checkSMSCode(String username, String SMS) {
        XhSmsLog xhSmsLog = xhSmsLogMapper.selectByUserName(username);
        if (StringUtil.isMobileNO((username))) { // 手机验证码校验
            Date date = new Date();
            long currentTime = date.getTime();
            long timeInterval;
            timeInterval = currentTime - xhSmsLog.getTime().getTime();
            if (username.equals(xhSmsLog.getUserName())
                    && SMS.equals(xhSmsLog.getSms())
                    && timeInterval < (long) (30 * 60 * 1000)) {
                xhSmsLog.setFlag(1);
                xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
                return true;
            }
        } else { // 邮箱验证码校验
            RequestBody requestBody = new FormBody.Builder()
                    .add("username", username).add("code", SMS).build();
            String result = sendMsg(ConstantString.PHP_URL_VERIFYEMAIL, requestBody, "");
            JSONObject object = JSONObject.parseObject(result);
            if (ResultEnum.SUCCESS.getCode().equals(object.getString("status"))) {
                xhSmsLog.setFlag(1);
                xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
                return true;
            }
        }
        return false;
    }

    /**
     * 密码重置
     */
    @Override
    public String passwordRest(String cellPhone, String originalPassword, String newPassword) {
        RequestBody requestBody;
        XhSmsLog xhSmsLog = new XhSmsLog();
        if (cellPhone != null) {
            xhSmsLog = xhSmsLogMapper.selectByUserName(cellPhone);
        }
        if (xhSmsLog.getFlag() == 1) {
            if (originalPassword == null) {
                requestBody = new FormBody.Builder()
                        .add("username", cellPhone)
                        .add("newPassword", newPassword).add("cmd", "17")
                        .build();
            } else {
                requestBody = new FormBody.Builder()
                        .add("username", cellPhone)
                        .add("newPassword", newPassword)
                        .add("originalPassword", originalPassword)
                        .add("cmd", "17").build();
            }
            String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, encryptToken(cellPhone));
            xhSmsLog.setFlag(0);
            xhSmsLogMapper.updateByPrimaryKeySelective(xhSmsLog);
            return result;
        }
        return ResultEnum.FAILED.getCode();
    }

    /**
     * 退出登录
     */
    @Override
    public String logout(int customerId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId + "").add("cmd", "15")
                .build();
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, "");
        return result;
    }

    /**
     * 判断是否注册过
     */
    @Override
    public boolean isRegisted(String username) {
        RequestBody requestBody = new FormBody.Builder()
                .add("username", username + "").add("cmd", "23").build();
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, encryptToken(username));
        if (result.equals("-2")) {
            return false;
        }
        JSONObject object = JSONObject.parseObject(result);
        if (ResultEnum.SUCCESS.getCode().equals(object.getString("status"))) {
            return false;
        }
        return true;
    }

    /**
     * 获取默认地址
     */
    @Override
    public String getDefaultAdress(HttpServletRequest httpServletRequest) {
        String customerId = httpServletRequest.getParameter("customerId");
        RequestBody requestBody = new FormBody.Builder().add("customerId",
                customerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_DEFAULTADDRESS, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 获取地址列表
     */
    @Override
    public String getAdressList(HttpServletRequest httpServletRequest) {
        String customerId = httpServletRequest.getParameter("customerId");
        RequestBody requestBody = new FormBody.Builder().add("customerId",
                customerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_ADDRESSLIST, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 设置默认地址
     */
    @Override
    public String setDefaultAddress(HttpServletRequest httpServletRequest) {
        String customerId = httpServletRequest.getParameter("customerId");
        String addressId = httpServletRequest.getParameter("addressId");
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId).add("addressId", addressId)
                .build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_SETDEFAULTADDRESS, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 新增地址
     */
    @Override
    public String addAddress(HttpServletRequest httpServletRequest) {
        String contactName = httpServletRequest.getParameter("contactName");
        String contactTel = httpServletRequest.getParameter("contactTel");
        String contactAddress = httpServletRequest
                .getParameter("contactAddress");
        String customerId = httpServletRequest.getParameter("customerId");
        String countryId = httpServletRequest.getParameter("countryId");
        String provinceId = httpServletRequest.getParameter("provinceId");
        String cityId = httpServletRequest.getParameter("cityId");
        String districtId = httpServletRequest.getParameter("districtId");
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId)
                .add("contactAddress", contactAddress)
                .add("contactName", contactName)
                .add("contactTel", contactTel).add("countryId", countryId)
                .add("provinceId", provinceId).add("cityId", cityId)
                .add("districtId", districtId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_ADDADDRESS, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 编辑地址
     */
    @Override
    public String editAddress(HttpServletRequest httpServletRequest) {
        String contactName = httpServletRequest.getParameter("contactName");
        String contactTel = httpServletRequest.getParameter("contactTel");
        String contactAddress = httpServletRequest
                .getParameter("contactAddress");
        String addressId = httpServletRequest.getParameter("addressId");
        String countryId = httpServletRequest.getParameter("countryId");
        String provinceId = httpServletRequest.getParameter("provinceId");
        String cityId = httpServletRequest.getParameter("cityId");
        String districtId = httpServletRequest.getParameter("districtId");
        RequestBody requestBody = new FormBody.Builder()
                .add("contactAddress", contactAddress)
                .add("contactName", contactName)
                .add("contactTel", contactTel).add("addressId", addressId)
                .add("countryId", countryId).add("provinceId", provinceId)
                .add("cityId", cityId).add("districtId", districtId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_EDITADDRESS, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 删除地址
     */
    @Override
    public String deleteAddress(HttpServletRequest httpServletRequest) {
        String addressId = httpServletRequest.getParameter("addressId");
        RequestBody requestBody = new FormBody.Builder().add("addressId",
                addressId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_DELADDRESS, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 获取地址信息列表
     */
    @Override
    public String getAddresTable(HttpServletRequest httpServletRequest) {
        String parentId = httpServletRequest.getParameter("parentId");
        String languageId = httpServletRequest.getParameter("languageId");
        RequestBody requestBody = new FormBody.Builder()
                .add("parentId", parentId).add("languageId", languageId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_GETADDRESSTABLE, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

}
